# coding=utf-8

import json
import datetime
import random
import string


def new_unique_id():
    return ''.join([random.choice(string.letters) for i in range(10)])


class JSONEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, datetime.datetime):
            return o.strftime('%Y-%m-%d %H:%M:%S.%f')
        if isinstance(o, datetime.date):
            return o.strftime('%Y-%m-%d')
        return json.JSONEncoder.default(self, o)


class SerializeObject(object):
    """
    序列化对象
    """

    def serialize(self):
        return json.dumps(self.to_dict(), cls=JSONEncoder)

    @classmethod
    def deserialize(cls, value):
        self = cls()
        v = json.loads(value)
        return self.from_dict(v)


class ShoppingCart(SerializeObject):
    """
    购物车
    """

    def __init__(self):
        self.cart_items = []

    def add(self, item):
        self.cart_items.append(item)

    def remove(self, item):
        item_index = -1
        for index, i in enumerate(self.cart_items):
            if i.unique_id == item.unique_id:
                item_index = index
                break

        if item_index != -1:
            self.cart_items.remove(item_index)

    def to_dict(self):
        d = []
        for item in self.cart_items:
            v = item.to_dict()
            d.append(v)
        return d

    def from_dict(self, d):
        self.cart_items = []
        for item in d:
            i = ShoppingCartItem()
            i.from_dict(item)
            self.cart_items.append(i)
        return self

    def __iter__(self):
        for item in self.cart_items:
            yield item

    def __str__(self):
        return str(self.to_dict())


class ShoppingCartItem(SerializeObject):
    """
    购物车数据项
    """

    def __init__(self):
        self.name = ''
        self.price = ''
        self.user_id = ''
        self.created = datetime.datetime.now()
        self.unique_id = new_unique_id()

    def init(self, name, price, user_id):
        self.name = name
        self.price = price
        self.user_id = user_id

    def to_dict(self):
        return {
            'name': self.name,
            'price': self.price,
            'user_id': self.user_id,
            'created': self.created,
            'unique_id': self.unique_id,
        }

    def from_dict(self, d):
        for key, value in d.iteritems():
            setattr(self, key, value)

        if self.created:
            self.created = datetime.datetime.strptime(self.created, '%Y-%m-%d %H:%M:%S.%f')

        return self

    def __str__(self):
        return str(self.to_dict())
